﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Interop;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Windows;
using System.Windows.Documents;
using System.Collections;
using System.IO;
using System.Diagnostics;
using System.Security.Policy;
using System.Threading;

namespace WpfApp1
{
    public static class Common
    {

        [DllImport("gdi32.dll", SetLastError = true)]
        private static extern bool DeleteObject(IntPtr hObject);
        public static ImageSource BitmapToImageSource(this Bitmap bitmap)
        {
            IntPtr hBitmap = bitmap.GetHbitmap();
            ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            // 记得要进行内存释放。否则会有内存不足的报错。
            if (!DeleteObject(hBitmap))
            {
                MessageBox.Show("内存释放错误！");
                throw new Win32Exception();
            }
            return wpfBitmap;
        }

        public static ImageSource IconToImageSource(Icon icon)
        {
            //拿到的是大图标
            Int32Rect rect = new Int32Rect(0, 0, 32, 32);
            ImageSource imageSource = Imaging.CreateBitmapSourceFromHIcon(icon.Handle,rect, BitmapSizeOptions.FromWidthAndHeight(256,256));

            return imageSource;
        }

        /// <summary>
        /// 获取地址
        /// </summary>
        /// <param name="start"></param>
        /// <param name="list"></param>
        public static void AddPathInfo(string start,out List<fileInfo> fileInfo)
        {
          
            FindInk findInk = new FindInk();
            IEnumerable<string> RecursiveFileSearchs = findInk.RecursiveFileSearch(start, "*.lnk");

            List<fileInfo> fileInfos = new List<fileInfo>();
            foreach (string filestr in RecursiveFileSearchs)
            {
                TryGetExeLargeIcon.TryGetExeLargeIconGo(filestr);
                if (TryGetExeLargeIcon.fileName=="")
                {
                    continue;
                }
                //if (!System.IO.File.Exists(TryGetExeLargeIcon.fileName))
                //{
                //    continue;
                //}
                fileInfo info = new fileInfo();
                info.fileImg=GetImageName(TryGetExeLargeIcon.fileName);
                info.fileName=TryGetExeLargeIcon.fileName;
                info.ExefilePath=TryGetExeLargeIcon.ExefilePath;
                fileInfos.Add(info);
               
            }
            fileInfo = fileInfos;
        }

        /// <summary>
        ///     获取图片路径
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetImageName(string name)
        {
            return MainWindow.folderToSave + @"imgs\" + name+".png";
        }

        /// <summary>
        /// 获取地址文件的内容
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public static string GetJsonFile(string filepath)
        {
            string json = string.Empty;
            using (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
                {
                    json = sr.ReadToEnd().ToString();
                }
            }
            return json;
        }



        [DllImport("user32.dll", EntryPoint = "PostMessage")]
        public static extern int PostMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        [DllImport("User32.dll ", EntryPoint = "FindWindow")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);//关键方法
        [DllImport("user32.dll", SetLastError = true)]
        private static extern int SendMessage(IntPtr HWnd, uint Msg, int WParam, int LParam);
        public const int WM_SYSCOMMAND = 0x112;
        public const int SC_MINIMIZE = 0xF020;
        public const int SC_MAXIMIZE = 0xF030;
        public const uint WM_SYSCOMMAND2 = 0x0112;
        public const uint SC_MAXIMIZE2 = 0xF030;
        [DllImport("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
        [DllImport("user32.dll")]
        public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

        /// <summary>
        /// 最大化或打开软件
        /// </summary>
        /// <param name="fileName"></param>
        public static void OpenSDRSharp(string fileName)
        {
            Process[] app = Process.GetProcessesByName(fileName);
            string ExefilePath=null;
            foreach (var itme in MainWindow.rootobject)
            {
                if (itme.fileName == fileName)
                {
                    ExefilePath=itme.ExefilePath;
                    break;
                }
            }
            if(ExefilePath == null)
            {
                return;
            }
            if (app.Length > 0)
            {
                bool isNotepadMinimized = GetMinimized(app[0].MainWindowHandle);
                if (!isNotepadMinimized)
                {
                    MiniMizeAppication(fileName); // 窗口被最小化了
                    return;
                }
                IntPtr handle = app[0].MainWindowHandle;
                SendMessage(handle, WM_SYSCOMMAND2, new IntPtr(SC_MAXIMIZE2), IntPtr.Zero);	// 最大化
                SwitchToThisWindow(handle, true);	// 激活
            }
            else
            {
                try
                {
                    System.Diagnostics.Process.Start(ExefilePath);
                }
                catch
                {
                    return;
                }    
            }
        }

        /// <summary>
        /// 最小化其他应用程序
        /// </summary>
        /// <param name="processName"></param>
        public static void MiniMizeAppication(string processName)
        {
            Process[] processs = Process.GetProcessesByName(processName);
            if (processs != null)
            {
                foreach (Process p in processs)
                {
                    IntPtr handle = FindWindow(null, p.MainWindowTitle);
                    PostMessage(handle, WM_SYSCOMMAND, SC_MINIMIZE, 0);
                }
            }
        }

        //获取窗体位置 最小化 最大化 隐藏 api
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);
        static UInt32 SW_SHOWMINIMIZED = 2;

        private struct WINDOWPLACEMENT
        {
            public int length;
            public int flags;
            public int showCmd;
            public System.Drawing.Point ptMinPosition;
            public System.Drawing.Point ptMaxPosition;
            public System.Drawing.Rectangle rcNormalPosition;
        }

        public static bool GetMinimized(IntPtr handle)
        {
            WINDOWPLACEMENT placement = new WINDOWPLACEMENT();
            placement.length = Marshal.SizeOf(placement);
            GetWindowPlacement(handle, ref placement);
            return placement.showCmd == SW_SHOWMINIMIZED;
            //1 = normal
            //2 = minimized
            //3 = maximized
        }

        public static bool IsRuning(string exeName)
        {
            var res = false;
            if (Process.GetProcessesByName(exeName).ToList().Count > 0)
            {
                res = true;
            }
            return res;
        }

    }

    public class fileInfo
    {
        public string fileImg { get; set; }
        public string fileName { get; set; }
        public string ExefilePath { get; set; }
    }
}
